import unittest, database
import services.AccountsService as AccountsService
from database import Currency, Money, Account

class ServiceTests(unittest.TestCase):

    def test_getAbsentAccount(self):
        account = AccountsService.getAccounts("admin", accountName="some absent name")
        self.assertEqual(None, account)

    def test_CreateAndUpdateAccount(self):
        self.recreateDB()
        account = Account("acc1")
        account.initialAmounts = [Money(123, AccountsService.getCurrency("UAH")), Money(456, AccountsService.getCurrency("USD"))]

        self.assertEqual(1, AccountsService.saveOrUpdateAccount("admin", account))

        updateAccount = Account("acc2")
        updateAccount.id = 1
        updateAccount.initialAmounts = [Money(100, AccountsService.getCurrency("UAH")), Money(400, AccountsService.getCurrency("EUR"))]

        self.assertEqual(1, AccountsService.saveOrUpdateAccount("admin", updateAccount))

        accounts = AccountsService.getAccounts("admin", id=1)
        self.assertEqual(accounts[0].name, "acc2")

        def moneyPredicate(money):
            return (money.amount == 100 and money.currency.code == "UAH") or \
                   (money.amount == 400 and money.currency.code == "EUR")
        self.assertEqual(len([money for money in accounts[0].initialAmounts if moneyPredicate(money)]) ,2)

    def recreateDB(self):
        import TestsHelper
        database.dropTables()
        database.create_db()
        TestsHelper.setupDatabase()

        
        
